package com.yakami.ocean;

import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Resources;

import com.squareup.leakcanary.LeakCanary;
import com.yakami.ocean.bean.UserInfo;
import com.yakami.ocean.model.SharePreferenceManager;
import com.yakami.ocean.utils.Tools;

import rx.schedulers.Schedulers;

public class AppManager extends Application {

    public static UserInfo mUser;
    public static Context context;
    public static Resources resources;

    @Override
    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();
        resources = getResources();
        //init leakCanary
        LeakCanary.install(this);
    }

    public static boolean isLoggedIn() {
        return mUser != null;
    }

    public static void logout() {
        mUser = null;
        ServerAPI.getOceanAPI()
                .outLogin()
                .subscribeOn(Schedulers.io());
        SharedPreferences.Editor editor = SharePreferenceManager.getUser().edit();
        editor.remove(SharePreferenceManager.User.KEY_COOKIES);
        editor.remove(SharePreferenceManager.User.KEY_USER_ID);
        editor.remove(SharePreferenceManager.User.KEY_USER_NAME);
        editor.remove(SharePreferenceManager.User.KEY_PORTRAIT_URL);
        editor.remove(SharePreferenceManager.User.KEY_PASSWORD);
        editor.apply();
    }

    public static UserInfo getLocalUser() {
        SharedPreferences tmp = SharePreferenceManager.getUser();
        UserInfo user = new UserInfo();
        user.id = tmp.getInt(SharePreferenceManager.User.KEY_USER_ID, -1);
        user.name = tmp.getString(SharePreferenceManager.User.KEY_USER_NAME, "");
        user.portraitUrl = tmp.getString(SharePreferenceManager.User.KEY_PORTRAIT_URL, "");
        user.isLogined = false;
        if (user.id == -1 || Tools.isEmpty(user.name)) {
            return null;
        }
        mUser = user;
        return user;
    }
}
